﻿//========================================
// All rights reserved (C) 2017-2100
// CLR 版本：	4.0.30319.42000
// 命名空间:	SFJDService
// 文 件 名：	FileReceive
// 作    者：	WooG
// 联系方式：	wooglle@163.com
// 创建时间：	2017/9/27 14:05:15
//========================================
using Common;
using Common.XmlHandle;
using SFJDService.SocketHandle;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Threading;

namespace SFJDService
{
    class FileReceive
    {
        IPAddress myIp = IPAddress.Parse(Dns.GetHostEntry(Dns.GetHostName()).AddressList.FirstOrDefault<IPAddress>(a => a.AddressFamily.ToString().Equals("InterNetwork")).ToString());
        internal static List<ClassTransCSInfo> tasks = new List<ClassTransCSInfo>(3);
        private static int maxLength = 1400;
        //private static int maxLength = 65500;
        private static Thread threadWatch = null;
        private static Socket socketWatch = null;
        static ReaderWriterLockSlim lockSlim = new ReaderWriterLockSlim();

        private static Dictionary<string, Socket> dict = new Dictionary<string, Socket>();

        public FileReceive()
        {
            if (Runtime.onReciving)
            {
                return;
            }
            else
            {
                BeginListening();
            }
        }

        /// <summary>
        /// 开始监听
        /// </summary>
        public void BeginListening()
        {
            Runtime.onReciving = true;
            try
            {
                socketWatch = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);//创建服务端负责监听的套接字，参数（使用IPV4协议，使用流式连接，使用Tcp协议传输数据）
                IPEndPoint endpoint = new IPEndPoint(this.myIp, Runtime.portFile);//创建包含Ip和port的网络节点对象
                socketWatch.Bind(endpoint);//将负责监听的套接字绑定到唯一的Ip和端口上
                socketWatch.Listen(30);//设置监听队列的长度
                threadWatch = new Thread(ListeningConnect);//创建负责监听的线程，并传入监听方法
                threadWatch.IsBackground = true;//设置为后台线程
                threadWatch.Start();//开始线程
                Runtime.Printf("开始监听：" + endpoint.Address + ":" + endpoint.Port);
            }
            catch(Exception e)
            {
                throw new Exception(e.ToString());
            }
            finally
            {
                if(socketWatch != null && socketWatch.Connected)
                {
                    socketWatch.Close();
                    socketWatch.Dispose();
                }
                Runtime.onReciving = false;
            }
        }

        /// <summary>
        /// 监听端口连接
        /// </summary>
        private void ListeningConnect()
        {
            while (Runtime.onReciving)//持续不断的监听客户端的请求
            {
                Socket connection = socketWatch.Accept();//开始监听 客户端连接请求，注意：Accept方法，会阻断当前的线程
                dict.Add(connection.RemoteEndPoint.ToString(), connection);//将与客户端通信的套接字对象connection添加到键值对集合中，并以客户端Ip做为健

                //创建通信线程
                ParameterizedThreadStart pts = new ParameterizedThreadStart(RecMsg);//带参数的线程
                Thread thradRecMsg = new Thread(pts);
                thradRecMsg.IsBackground = true;
                thradRecMsg.Start(connection);
            }
        }


        /// <summary>
        /// 接收消息
        /// </summary>
        /// <param name="socketClientPara"></param>
        private void RecMsg(object socketClientPara)
        {
            bool hasXml = false;//等待xml文件写完
            for (int i = 0; i < 10; i++)
            {
                if (Runtime.xmlDownload.isThereGuid(tasks[0].TransGuid))
                {
                    hasXml = true;
                    break;
                }
                else
                {
                    Thread.Sleep(200 * i);
                }
            }
            if (!hasXml)
            {
                throw new System.Exception("错误：读取xml文档未找到指定任务 " + this.GetType());
            }


            Socket socketClient = socketClientPara as Socket;
            while (true)
            {
                //定义一个接收用的缓存区（100M字节数组）
                //byte[] arrMsgRec = new byte[1024 * 1024 * 100];
                //将接收到的数据存入arrMsgRec数组,并返回真正接受到的数据的长度   
                if (socketClient.Connected)
                {
                    int size = 0;
                    
                    ClassTransportInfo transInfo = Runtime.xmlDownload.GetTransInfo(tasks[0].TransGuid);
                    //while((transInfo = new XmlTransport(Common.XmlHandle.TransportType.Download, Runtime.pathTemp).GetTransInfo(tasks[0].TransGuid)).RootPath == null) { }

                    string[] buf1 = transInfo.RootPath.Split('\\');
                    string lastFolderName = buf1[buf1.Length - 2];//获取文件列表中所有文件的总文件夹名
                    string fileRootPath;
                    if (transInfo.Files.Count == 1)
                    {
                        fileRootPath = Runtime.thisUser.InPath + tasks[0].NameSend;//获得用户保存文件的路径
                    }
                    else
                    {
                        fileRootPath = Runtime.thisUser.InPath + tasks[0].NameSend + "\\" + lastFolderName;//获得用户保存文件的路径 + 总文件件名
                    }

                    long leftLen = transInfo.Files[0].FileSize;       //剩余的长度
                                                                      //long receiveLen = 0;    //已经接收的长度
                    int readLen = maxLength;//读取的长度
                    int readIndex = 0;      //读取的位置
                    int transIndex = 0; //files的index
                    int offset = 0;
                    //bool isFileEnd = false;
                    //bool isTransEnd = false;
                    
                    string fileFullPath = fileRootPath + '\\' + transInfo.Files[transIndex].RelativePath;//获取文件的完整路径
                    string[] buf2 = fileFullPath.Split('\\');
                    string fileSavePath = fileFullPath.Substring(0, fileFullPath.Count() - buf2.Last().Count());
                    if (!Directory.Exists(fileSavePath))
                    {
                        Directory.CreateDirectory(fileSavePath);
                    }

                    lockSlim.EnterWriteLock();//进入写锁
                    //创建文件流，然后让文件流来根据路径创建一个文件
                    FileStream fs = new FileStream(fileFullPath, FileMode.Create); 
                    //从终端不停的接受数据，然后写入文件里面，只到接受到的数据为0为止，则中断连接
                    //receiveLen += maxLength;
                    //因为终端每次发送文件的最大缓冲区是512 + 1字节，所以每次接收也是定义为512字节
                    byte[] buffer = new byte[maxLength];
                    int sizeLast = 0;

                    while (socketClient.Connected && (size = socketClient.Receive(buffer, 0, buffer.Length, SocketFlags.None)) > 0)
                    {
                        if (saveFile(fileRootPath, ref buffer, ref offset, ref sizeLast, size, ref leftLen, ref transInfo, ref transIndex, ref readIndex, ref fs))
                        {
                            break;
                        }
                    }
                    Runtime.Printf("           接收中断");

                    lockSlim.ExitWriteLock();
                    //new XmlTransport(Common.XmlHandle.TransportType.Download, Runtime.pathTemp).RemoveByGuid(tasks[0].TransGuid);
                    try
                    {
                        Runtime.xmlDownload.RemoveByGuid(tasks[0].TransGuid);

                        tasks.RemoveAt(0);
                        CloseTcpSocket();
                        dict.Remove(socketClient.RemoteEndPoint.ToString());
                    }
                    catch(Exception e)
                    {
                        throw;
                    }
                    break;
                }
                else
                {
                    CloseTcpSocket();
                    break;
                }
            }
        }


        private int Receive(Socket socket, byte[] buffer, int outTime)
        {
            if (socket == null || socket.Connected == false)
            {
                throw new ArgumentException("socket为null，或者未连接到远程计算机");
            }
            if (buffer == null || buffer.Length == 0)
            {
                throw new ArgumentException("buffer为null ,或者长度为 0");
            }

            buffer.Initialize();
            int left = buffer.Length;
            int curRcv = 0;
            int hasRecv = 0;
            int flag = 0;

            try
            {
                while (true)
                {
                    if (socket.Poll(outTime * 1000, SelectMode.SelectRead) == true)
                    {
                        // 已经有数据等待接收
                        curRcv = socket.Receive(buffer, hasRecv, left, SocketFlags.None);
                        left -= curRcv;
                        hasRecv += curRcv;

                        // 数据已经全部接收 
                        if (left == 0)
                        {
                            flag = 0;
                            break;
                        }
                        else
                        {
                            // 数据已经部分接收
                            if (curRcv > 0)
                            {
                                continue;
                            }
                            else  // 出现错误
                            {
                                flag = -2;
                                break;
                            }
                        }
                    }
                    else // 超时退出
                    {
                        flag = -1;
                        break;
                    }
                }
            }
            catch (SocketException)
            {
                //Log
                flag = -3;
            }
            return flag;
        }

        private bool saveFile(string fileRootPath, ref byte[] buffer, ref int offset, ref int sizeLast, int sizeNow, ref long leftLen, ref ClassTransportInfo trans, ref int transIndex, ref int readIndex, ref FileStream fs)
        {
            //Log.ToConsole("xx" + transIndex + "  " + trans.Files[transIndex].RelativePath + "  " + trans.Files[transIndex].FileSize + "  " + offset + "   " +
            //            leftLen + "   " + sizeLast + "   " + sizeNow);
            bool b = false;
            int readLen = 0;
            bool isFileEnd = false;
            bool isMultiInOne = false;
            leftLen -= sizeLast;

            byte[] buff = buffer.Skip(5).ToArray();

            if (leftLen > sizeNow - offset)
            {
                readLen = sizeNow - offset;
                fs.Write(buffer, offset, readLen);
            }
            else if (leftLen == sizeNow - offset)
            {
                readLen = sizeNow - offset;
                isFileEnd = true;
                fs.Write(buffer, offset, readLen);
            }
            else       //leftLen < sizeNow
            {
                readLen = (int)leftLen;
                isFileEnd = true;
                fs.Write(buffer, offset, readLen);
                if ((long)offset + (long)readLen < sizeNow)
                {
                    isMultiInOne = true;
                }
            }
            readIndex++;
            sizeLast = readLen;

            if (isFileEnd)
            {
                fs.Flush();
                fs.Close();

                if (transIndex == trans.Files.Count - 1)
                {
                    return true;
                }
                transIndex++;
                string fileFullPath = fileRootPath + '\\' + trans.Files[transIndex].RelativePath;
                string[] buf = fileFullPath.Split('\\');
                string fileSavePath = fileFullPath.Substring(0, fileFullPath.Count() - buf.Last().Count());
                if (!Directory.Exists(fileSavePath))
                {
                    Directory.CreateDirectory(fileSavePath);
                }
                fs = new FileStream(fileFullPath, FileMode.Create);
                readIndex = 0;
                sizeLast = 0;
                offset += readLen;
                isFileEnd = false;
                leftLen = trans.Files[transIndex].FileSize;
                if (isMultiInOne)
                {
                    b = saveFile(fileRootPath, ref buffer, ref offset, ref sizeLast, sizeNow, ref leftLen, ref trans, ref transIndex, ref readIndex, ref fs);
                    isMultiInOne = false;
                }
                offset = 0;
            }
            return b;
        }

        /// <summary>
        /// 关闭连接
        /// </summary>
        public void CloseTcpSocket()
        {
            dict.Clear();
            if (tasks.Count > 0)
            {
                Runtime.Printf(tasks.Count + "   65403端口未  关闭");
                //Synchronize syn = new Synchronize();
                //syn.SendUdp("1305" + tasks[0].TransGuid + '♠' + tasks[0].ReciveIP + '♠' + tasks[0].ReciceName);
                Launcher.SendMsg2All(typeof(PH05SeStratSend).GetDictianaryKey(), tasks[0].TransGuid + "♠" + tasks[0].IPRecive + "♠" + tasks[0].NameRecive + "♠" + tasks[0].IPSend + "♠" + tasks[0].NameSend);
            }
            else
            {
                threadWatch.Abort();
                socketWatch.Close();
                Runtime.onReciving = false;
                Runtime.Printf(myIp + ".65403端口关闭");
                //ProcessStartInfo processStartInfo = new ProcessStartInfo(Runtime.programPath + "\\SFJDPopup.exe", "1 接收到" + this.sendName + "发送的文件。");
                //Process.Start(processStartInfo);
            }
            //ProcessStartInfo processStartInfo = new ProcessStartInfo(Runtime.programPath + "\\SFJDPopup.exe", "1 接收到" + sendName + "发送的文件。");
            //Process.Start(processStartInfo);
        }
    }
}
